package com.qdsg.ysg.doctor.ui.kotlin

import android.annotation.TargetApi
import android.app.ActivityManager
import android.os.Build
import android.text.TextUtils
import com.ainemo.sdk.otf.NemoSDK
import com.ainemo.sdk.otf.NemoSDKInitCallBack
import com.ainemo.sdk.otf.Settings
import com.ainemo.sdk.otf.VideoConfig
import com.qdsg.ysg.doctor.R
import com.qdsg.ysg.doctor.base.BaseApplication
import com.qdsg.ysg.doctor.base.BaseLoginActivity
import com.qdsg.ysg.doctor.ui.MainActivity
import com.qdsg.ysg.doctor.ui.activity.mine.WxLoginActivity
import com.qdsg.ysg.doctor.ui.dialog.PermissionDialog
import com.qdsg.ysg.doctor.util.AES128
import com.qdsg.ysg.doctor.util.ToastUtil
import com.qdsg.ysg.doctor.util.UtilString
import com.rest.business.RestProxy
import com.rest.client.RestClient
import com.rest.response.LoginResponse
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import jz.joyoung.robot.util.LogUtil
import jz.joyoung.robot.util.PreferencesHelper

/**
 * Description
 * Created by lbj on 2021/10/11 9:32
 */
class AtyWelcome : BaseLoginActivity() {

    private lateinit var mPermissionDialog: PermissionDialog

    private var token: String? = null

    // 所需的全部权限
//    val PERMISSIONS = arrayOf(Manifest.permission.READ_PHONE_STATE)
//    private lateinit var mPermissionsChecker: PermissionsChecker // 权限检测器

    override fun initData() {
        token = PreferencesHelper.getInstance().getString(this, "token")
        BaseApplication.xyAccount = PreferencesHelper.getInstance().getString(this, "xyAccount")
        BaseApplication.xyPassword = PreferencesHelper.getInstance().getString(this, "xyPassword")
        val isAgainApp = PreferencesHelper.getInstance().getBoolean(mContext, "isAgainApp")

        if (!isAgainApp) { //第一次安装弹出隐私
            showPermissionDialog()
        } else {
            init()
        }
    }

    override fun getLayoutResource(): Int = R.layout.aty_welcome

    override fun initViews() {
    }

    private fun showPermissionDialog() {
        mPermissionDialog = PermissionDialog.newInstance()
        mPermissionDialog.show(supportFragmentManager, "mPermissionDialog")
        mPermissionDialog.setmListener(object : PermissionDialog.OnItemClickListener {
            override fun onConfirm() {
                init()
//                checkPermission()
            }

            override fun onCancel() {
                ToastUtil.showToastCenter(mContext, "同意后可继续使用")
                exitAPP()
            }
        })
    }

//    @SuppressLint("CheckResult")
//    fun checkPermission() {
//        mPermissionsChecker = PermissionsChecker(mContext)
//        // 缺少权限时, 进入权限配置页面
//        if (mPermissionsChecker.lacksPermissions(*PERMISSIONS)) {
//            val applyPermissionDialog = ApplyPermissionDialog.newInstance("1", true)
//            applyPermissionDialog.show(supportFragmentManager, "applyPermissionDialog")
//            applyPermissionDialog.setmListener(object : ApplyPermissionDialog.OnItemClickListener {
//                @RequiresApi(Build.VERSION_CODES.O)
//                override fun onConfirm() {
//                    val permissions = RxPermissions(this@AtyWelcome)
//                    permissions.request(Manifest.permission.READ_PHONE_STATE)
//                            .subscribe { aBoolean: Boolean ->
//                                LogUtil.e(TAG, "request permission result:$aBoolean")
//                                init()
//                            }
//                }
//
//                override fun onCancel() {}
//            })
//        } else {
//            init()
//        }
//    }


    private fun init() {
        initXySDK()
        PreferencesHelper.getInstance().set(mContext, "isAgainApp", true)
        if (UtilString.isEmpty(token)) {
            startActivity(WxLoginActivity::class.java)
            finish()
        } else {
            RestClient.getInstance().token = token
            login()
        }
    }

    private fun login() {
        val username = PreferencesHelper.getInstance().getString(this, "username")
        val password = PreferencesHelper.getInstance().getString(this, "password")
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            startActivity(WxLoginActivity::class.java)
            finish()
            return
        }
        try {
            RestProxy.getInstance().login(AES128.encryptStringAES(username, "7t3e506jaa10xbd4"), AES128.encryptStringAES(password, "7t3e506jaa10xbd4"), "", object : Observer<LoginResponse?> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(loginResponse: LoginResponse) {
                    checkServiceRunning(mContext)
                    BaseApplication.currentUserId = loginResponse.data.userId
                    BaseApplication.name = loginResponse.data.name
                    BaseApplication.avatar = loginResponse.data.avatar
                    BaseApplication.sex = loginResponse.data.sex
                    BaseApplication.userType = loginResponse.data.hosType
                    BaseApplication.isAudit = loginResponse.data.isAudit
                    RestClient.getInstance().token = loginResponse.data.token
                    startActivity(MainActivity::class.java)
                    finish()
                }

                override fun onError(e: Throwable) {
                    startActivity(WxLoginActivity::class.java)
                    finish()
                }

                override fun onComplete() {}
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 小鱼sdk初始化
     */
    private fun initXySDK() {
        val settings = Settings("3e816492058911e7a31d000c29971af5")
        settings.privateCloudAddress = "39.172.69.238:7443"
        settings.isUiNeedSpeakers = true
        settings.videoMaxResolutionTx = VideoConfig.VD_1280x720
        settings.defaultCameraId = 1
        NemoSDK.getInstance().init(this, settings, object : NemoSDKInitCallBack {
            override fun nemoSdkInitSuccess() {
                LogUtil.e("小鱼SDK初始化成功")
            }

            override fun nemoSdkInitFail(s: String, s1: String) {
                LogUtil.e("SDK初始化失败")
            }
        })
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun exitAPP() {
        val activityManager = mContext.applicationContext.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val appTaskList = activityManager.appTasks
        for (appTask in appTaskList) {
            appTask.finishAndRemoveTask()
        }
    }
}